const { openDatabase } = require('../index');

function getDb() {
    return openDatabase();
}

function appendLog(jobId, level, message, meta = null) {
    const db = getDb();
    const stmt = db.prepare(
        'INSERT INTO download_logs (job_id, level, message, meta, created_at) VALUES (?, ?, ?, ?, datetime(\'now\'))'
    );
    const metaString = meta ? JSON.stringify(meta) : null;
    stmt.run(jobId, level, message, metaString);
}

function listLogs(jobId, limit = 200, offset = 0) {
    const db = getDb();
    return db
        .prepare(
            'SELECT * FROM download_logs WHERE job_id = ? ORDER BY created_at ASC LIMIT ? OFFSET ?'
        )
        .all(jobId, limit, offset);
}

module.exports = {
    appendLog,
    listLogs,
};


